package com.qf.jwt.security.handler;

import com.qf.common.core.domain.ResponseResult;
import com.qf.common.domain.admin.dos.SysUser;
import com.qf.common.utils.ServletUtils;
import com.qf.common.domain.admin.vo.LoginResultVO;
import com.qf.common.domain.admin.vo.UserInfoVO;
import com.qf.jwt.util.BeanUtils;
import com.qf.jwt.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import com.qf.common.domain.admin.dos.SysRole;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : sin
 * @date : 2024/6/11 13:01
 * @Description : 自定义登录成功响应
 */
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");
        if (authentication.getPrincipal() instanceof SysUser) {
            SysUser user = (SysUser) authentication.getPrincipal();
            UserInfoVO userInfoVo = new UserInfoVO(user.getId(), user.getUsername(),user.getNickname(), user.getAvatar(), user.getEmail(), user.getMobile(), user.getGender(), user.getRoles().get(0).getName(), user.getContent(), user.getCreateTime());

//            log.info("登录成功，用户信息：{}", sysUser);
            // 获取token  封装
            List<String> roles = user.getRoles().stream().map(SysRole::getCode).collect(Collectors.toList());
            //获取当前时间戳
            Long expireTime = BeanUtils.getBean(JwtUtil.class).getExpriTime();

            String accessToken = BeanUtils.getBean(JwtUtil.class).token(authentication);
            String refreshToken = BeanUtils.getBean(JwtUtil.class).refreshToken(authentication);
            // 通过响应流封装数据返回给前端
            ServletUtils.renderString(response, ResponseResult.success(new LoginResultVO(user.getUsername(), user.getAvatar(),user.getNickname(),roles,userInfoVo,accessToken,refreshToken,expireTime)));
        }
    }
}